//
//  HBWithdrawCtrl.m
//  HuoBao
//
//  Created by sky on 15/12/3.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBWithdrawCtrl.h"
#import "CustomTradePassword.h"
#import "CustomSuggestionAlert.h"
#import "HBModifyPwdFirstCtrl.h"
#import "NetCenter.h"
#import "HBUserConfirmDistillParam.h"
#import "HBUserConfirmDistillParser.h"
#import "HBUserConfirmDistillInfo.h"
#import "NSString+MKNetworkKitAdditions.h"
#import "HBLoginManager.h"
#import "HBInvestSuccessCtrl.h"
#import "HBGetTraingPwdLockStatusParam.h"
#import "HBGetTraingPwdLockStatusParser.h"
#import "HBGetTraingPwdLockStatusInfo.h"
#import "NetCenter.h"
#import "HBLoginManager.h"
#import "CustomSuggestionAlert.h"
@interface HBWithdrawCtrl ()<UITextFieldDelegate>
{
    UIScrollView *_bgview;
    UILabel *_money;
    UILabel *_banknum;
    UIImageView *_bankvi;
    UILabel *_frelbl;
    UITextField *_drawmoney;
    UIButton *_drawBtn;
    unichar _firchar;
}

@property (strong , nonatomic)HBGetTraingPwdLockStatusInfo *iteminfo;

@end

@implementation HBWithdrawCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

-(void)buildLayout{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextFieldTextDidChangeNotification object:nil];
    
    self.title = @"提现";
    [self addTap];
    
    _bgview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _bgview.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_bgview];

    
    UILabel *titile = [self LabelWithRect:CGRectMake(0, 58/2, SCREEN_WIDTH, 14) textColor:[LCCommon getColor:@"666666"] textstr:@"可取出金额(元)" textfont:14 textstyle:NSTextAlignmentCenter];
    [_bgview addSubview:titile];
    
    
    _money = [self LabelWithRect:CGRectMake(0, titile.origin.y + 14 + 25, SCREEN_WIDTH, 55) textColor:[LCCommon getColor:@"fa9838"] textstr:self.userDistillInfo.accountMoney textfont:55 textstyle:NSTextAlignmentCenter];
    [_bgview addSubview:_money];
    
    UIView *line = [self makeLinewithRect:CGRectMake(15, _money.origin.y + 55 + 40, SCREEN_WIDTH - 30, .5) Color:[LCCommon getColor:@"585858"] addview:_bgview];
    
    [self makeLinewithRect:CGRectMake(15, line.origin.y + 45, SCREEN_WIDTH - 30, .5) Color:[LCCommon getColor:@"585858"] addview:_bgview];
    
    UILabel *jine = [self LabelWithRect:CGRectMake(15,line.origin.y + (45/2 - 16/2) , 16 * 4 + 9, 16) textColor:[LCCommon getColor:@"b1b1b1"] textstr:@"金额(元)" textfont:16 textstyle:NSTextAlignmentLeft];
    [_bgview addSubview:jine];
    
    NSString *str = self.userDistillInfo.bankCardShort;
    CGSize strsize = [str sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
    
    _banknum = [self LabelWithRect:CGRectMake(SCREEN_WIDTH - 15 - strsize.width, jine.origin.y, 4 * 16, 16) textColor:[LCCommon getColor:@"b1b1b1"] textstr:str textfont:16 textstyle:NSTextAlignmentLeft];
    [_bgview addSubview:_banknum];
    
    _bankvi = [[UIImageView alloc]initWithFrame:CGRectMake(_banknum.origin.x - 5 - 20,line.origin.y +  45/2 - 10, 20, 20)];
    [_bankvi setImage:[UIImage imageNamed:self.userDistillInfo.bankCode]];
    [_bgview addSubview:_bankvi];
    
    _drawmoney = [self TextFieldWithRect:CGRectMake(jine.origin.x + jine.size.width,line.origin.y, _bankvi.origin.x -(jine.origin.x + 15 + jine.size.width) , 45) leftImage:nil placeHold:@"请输入提现金额" index:1];
    _drawmoney.keyboardType = UIKeyboardTypeDecimalPad;
    
    
    NSString *haikeyi = [NSString stringWithFormat:@"今日还可以提现%@次",self.userDistillInfo.restDistillTimes];
    _frelbl = [self LabelWithRect:CGRectMake(15, line.origin.y + 45 + 12, SCREEN_WIDTH/2, 14) textColor:[LCCommon getColor:@"777777"] textstr:haikeyi textfont:14 textstyle:NSTextAlignmentLeft];
    [_bgview addSubview:_frelbl];
    
    
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:haikeyi];
    [noteStr addAttribute:NSForegroundColorAttributeName value:[LCCommon getColor:@"f34546"] range:NSMakeRange(7, 1)];
    [_frelbl setAttributedText:noteStr];
    
    UILabel *free = [self LabelWithRect:CGRectMake(SCREEN_WIDTH - 15 - 4 * 14, _frelbl.origin.y, 4 * 14, 14) textColor:[LCCommon getColor:@"51b724"] textstr:@"免手续费" textfont:14 textstyle:NSTextAlignmentLeft];
    [_bgview addSubview:free];
    
    NSString *maxDistill = [[NSString alloc]init];
    if ([self.userDistillInfo.distillMaxMoney integerValue] > 10000 || [self.userDistillInfo.distillMaxMoney integerValue] == 10000) {
        maxDistill = [NSString stringWithFormat:@"单笔最大限额%ld万",[self.userDistillInfo.distillMaxMoney integerValue]/10000];
    }else if([self.userDistillInfo.distillMaxMoney integerValue] > 1000 || [self.userDistillInfo.distillMaxMoney integerValue] == 1000){
        maxDistill = [NSString stringWithFormat:@"单笔最大限额%ld千",[self.userDistillInfo.distillMaxMoney integerValue]/1000];
    }else if ([self.userDistillInfo.distillMaxMoney integerValue] > 100 || [self.userDistillInfo.distillMaxMoney integerValue] == 100){
        maxDistill = [NSString stringWithFormat:@"单笔最大限额%ld百",[self.userDistillInfo.distillMaxMoney integerValue]/100];
    }
    
    UILabel *xiane = [self LabelWithRect:CGRectMake(15, _frelbl.origin.y + 14 + 10, SCREEN_WIDTH/2, 14) textColor:[LCCommon getColor:@"f34546"] textstr:maxDistill textfont:14 textstyle:NSTextAlignmentLeft];
    [_bgview addSubview:xiane];
    
    
    _drawBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, xiane.origin.y + 14 + 25, SCREEN_WIDTH - 30, 45)];
    [_drawBtn setBackgroundColor:[LCCommon getColor:@"f24545"] forState:UIControlStateNormal];
    [_drawBtn setBackgroundColor:[LCCommon getColor:@"bd3737"] forState:UIControlStateDisabled];
    _drawBtn.enabled = NO;
    [_drawBtn setTitle:@"马上提现" forState:UIControlStateNormal];
    _drawBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [_drawBtn setTitleColor:[LCCommon getColor:@"ffffff"] forState:UIControlStateNormal];
    [_drawBtn setTitleColor:[LCCommon getColor:@"fd7a7a"] forState:UIControlStateDisabled];
    _drawBtn.clipsToBounds = YES;
    _drawBtn.layer.cornerRadius = 4;
    [_drawBtn addTarget:self action:@selector(btntoDraw) forControlEvents:UIControlEventTouchUpInside];
    [_bgview addSubview:_drawBtn];

    
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)doTouch:(UIGestureRecognizer *)sender{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(UILabel *)LabelWithRect:(CGRect)rect textColor:(UIColor *)color textstr:(NSString *)str textfont:(int)font textstyle:(NSTextAlignment)aligment{
    UILabel *label = [[UILabel alloc] initWithFrame:rect];
    label.textColor = color;
    label.text = str;
    label.font = [UIFont systemFontOfSize:font];
    label.textAlignment = aligment;
    label.numberOfLines = 0;
    return label;
}

- (UITextField *)TextFieldWithRect:(CGRect)rect leftImage:(UIImage *)image placeHold:(NSString *)placeHold index:(NSInteger)index
{
    UITextField *text = [[UITextField alloc] initWithFrame:rect];
    text.placeholder = placeHold;
    text.backgroundColor = [UIColor clearColor];
    text.delegate = self;
    text.font = [UIFont systemFontOfSize:14];
    text.textColor = [LCCommon getColor:@"ffffff"];
    [text setValue:[LCCommon getColor:@"585858"] forKeyPath:@"_placeholderLabel.textColor"];
    
    
    [_bgview addSubview:text];
//    UIView *line = [[UIView alloc]init];
//    if (index == 1) {
//        line = [[UIView alloc] initWithFrame:CGRectMake(40, rect.size.height + rect.origin.y + 2, rect.size.width, .5)];
//    }else{
//        line = [[UIView alloc] initWithFrame:CGRectMake(40, rect.size.height + rect.origin.y + 2, SCREEN_WIDTH - 80, .5)];
//    }
//    
//    line.backgroundColor = [LCCommon getColor:@"a8a8a8"];
//    [_bgview addSubview:line];
//    line = nil;
    return text;
}

-(UIView *)makeLinewithRect:(CGRect)rect Color:(UIColor *)color addview:(UIView *)vi{
    UIView *line = [[UIView alloc]initWithFrame:rect];
    line.backgroundColor = color;
    [vi addSubview:line];
    return line;
}

-(void)textDidChange{
    if (_drawmoney.text.length > 0) {
        _drawBtn.enabled = YES;
    }else{
        _drawBtn.enabled = NO;
    }
}


-(void)btntoDraw{
    
    if ([_drawmoney.text doubleValue] > [self.userDistillInfo.accountMoney doubleValue]) {
        DISSMISS_ERR(@"余额不足");
        return;
    }
    
    if ([_drawmoney.text doubleValue] <= 0 || [_drawmoney.text doubleValue] > [self.userDistillInfo.distillMaxMoney doubleValue] || [_drawmoney.text doubleValue] > [self.userDistillInfo.accountMoney doubleValue]) {
        DISSMISS_ERR(@"请输入正确金额");
        return;
    }
    if ([self.userDistillInfo.restDistillTimes intValue] == 0) {
        DISSMISS_ERR(@"提现次数已用完");
    }else{
        [self requestGetTraingPwdLockStatus];
    }
}


-(void)PasswordFordeal{
    if ([self.iteminfo.tradingPwdLockStatus isEqualToString:@"1"]) {
        
        CustomSuggestionAlert *sugg = [[CustomSuggestionAlert alloc]init];
        [sugg showTradPasswordAlertView];
        sugg.buttonClicked = ^(NSInteger tag){
            if (tag == 2501) {
                HBModifyPwdFirstCtrl* reTradPswVC = [[HBModifyPwdFirstCtrl alloc] init];
                reTradPswVC.modifyType = ModifyPwdType_BuyPwd;
                reTradPswVC.isFromTiXian = YES;
                [self.navigationController pushViewController:reTradPswVC animated:YES];
            }
        };
        
    }else if([self.iteminfo.tradingPwdLockStatus isEqualToString:@"0"]){
        CustomTradePassword *password = [[CustomTradePassword alloc]init];
        password.enterTradPassword = ^(NSString* password){
            LLog(@"输入的交易密码%@",password);
        };
        password.isSuccess = ^(BOOL isSuccess,HBUserConfirmDistillInfo* info,NSString* message){
            if (isSuccess == YES) {
                HBInvestSuccessCtrl *scu = [[HBInvestSuccessCtrl alloc]init];
                scu.confirmDistillInfo = info;
                [self.navigationController pushViewController:scu animated:YES];
            }else if(isSuccess == NO){
                DISSMISS_ERR(message);
            }
        };
        password.pswError = ^(BOOL isRight){
            CustomSuggestionAlert* suggestionView = [[CustomSuggestionAlert alloc] init];
            if (isRight == NO) {
                [suggestionView showTradPasswordAlertView];
            }
            suggestionView.buttonClicked = ^(NSInteger tag){
                if (2501 == tag) {
                    HBModifyPwdFirstCtrl* reTradPswVC = [[HBModifyPwdFirstCtrl alloc] init];
                    reTradPswVC.isFromTiXian = YES;
                    reTradPswVC.modifyType = ModifyPwdType_BuyPwd;
                    [self.navigationController pushViewController:reTradPswVC animated:YES];
                }
            };
        };
        password.distillMoney = _drawmoney.text;
        [password showTradPasswordAlertView];
    }
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    BOOL isHaveDian = YES;
    if ([_drawmoney.text rangeOfString:@"."].location==NSNotFound) {
        isHaveDian=NO;
    }
    if ([string length]>0)
    {
        unichar single=[string characterAtIndex:0];//当前输入的字符
        if ((single >='0' && single<='9') || single=='.')//数据格式正确
        {
            //首字母不能为0和小数点
            if([_drawmoney.text length]==0){
                if(single == '.'){
                    [_drawmoney.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
                if (single == '0') {
//                    [_drawmoney.text stringByReplacingCharactersInRange:range withString:@""];
//                    return NO;
                    _firchar = single;
                    return YES;
                }
            }
            if (single=='.')
            {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian=YES;
                    return YES;
                }else
                {
                    [_drawmoney.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            else
            {
                if ([_drawmoney.text isEqualToString:@"0"] && !isHaveDian) {
                    [_drawmoney.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
                if (isHaveDian)//存在小数点
                {
                    //判断小数点的位数
                    NSRange ran=[_drawmoney.text rangeOfString:@"."];
                    NSInteger tt = range.location-ran.location;
                    if (tt <= 2){
                        return YES;
                    }else{
        
                        return NO;
                    }
                }
                else
                {
                    return YES;
                }
            }
        }else{//输入的数据格式不正确
            [_drawmoney.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    }
    else
    {
        return YES;
    }
}


-(void)doBack{
//    [super doBack];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)requestGetTraingPwdLockStatus{
    HBGetTraingPwdLockStatusParam *param = [[HBGetTraingPwdLockStatusParam alloc]init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    HBGetTraingPwdLockStatusParser *parser = [[HBGetTraingPwdLockStatusParser alloc]init];
    [CustomLoadingView showHudToView:self.view];
    [NetCenter getDataFromURL:Method_getTraingPwdLockStatus params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (myResult.code == 0)
        {
            HBGetTraingPwdLockStatusInfo *info = (HBGetTraingPwdLockStatusInfo *)myResult.result;
            self.iteminfo = info;
            [self PasswordFordeal];
        }
        else
        {
            DISSMISS_ERR(myResult.message);
        }

        
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR([error description]);
    }];
}

//-(void)requestToDistill{
//    HBUserConfirmDistillParam *param = [[HBUserConfirmDistillParam alloc]init];
//    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
//    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
//    param.distillMoney = _drawmoney.text;
//    NSString *str = @"524813";
//    param.tradingPwd = str.md5;
//    [CustomLoadingView showHudToView:nil];
//    HBUserConfirmDistillParser *parser = [[HBUserConfirmDistillParser alloc]init];
//    [NetCenter postDataFromURL:Method_userConfirmDistill params:param parser:parser result:^(ParserResult *myResult) {
//        [CustomLoadingView hideHudForView:nil];
//        if (myResult.code == 0)
//        {
//            HBUserConfirmDistillInfo *info = (HBUserConfirmDistillInfo *)myResult.result;
//            HBInvestSuccessCtrl *scu = [[HBInvestSuccessCtrl alloc]init];
//            scu.confirmDistillInfo = info;
//        }
//        else
//        {
//            DISSMISS_ERR(myResult.message);
//        }
//
//    } failure:^(NSError *error) {
//        [CustomLoadingView hideHudForView:nil];
//        DISSMISS_ERR([error description]);
//    }];
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
